package com.xinyue.server.framework.server;

import com.google.common.util.concurrent.RateLimiter;
import com.xinyue.server.framework.common.GameServerUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Author 王广帅
 * @Date 2021/4/11 15:08
 */
public class RequestFilterHandler extends ChannelInboundHandlerAdapter {
    private RateLimiter singleRateLimiter;
    /**
     * 全局限流器
     */
    private RateLimiter globalRateLimiter;
    private static Logger logger = LoggerFactory.getLogger(RequestFilterHandler.class);


    public RequestFilterHandler(RateLimiter globalRateLimiter, RateLimiter singleRateLimiter) {
        this.globalRateLimiter = globalRateLimiter;
        this.singleRateLimiter = singleRateLimiter;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        boolean flag = singleRateLimiter.tryAcquire();
        boolean globalFlag = globalRateLimiter.tryAcquire();
        if (flag && globalFlag) {
            ctx.fireChannelRead(msg);
        } else {
            logger.error("请求太频繁，不处理，直接返回,channelId:{},singleLimit:{},globalLimit:{}", GameServerUtil.getChannelId(ctx.channel()), flag, globalFlag);
        }
    }
}
